package com.block.datapush.service.apipush;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RongHuiJinFuUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 融汇金服 API
 */
@Service
public class RongHuiJinFuApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiCode = pushApiKeyParam.getApiCode();
        String key = pushApiKeyParam.getApiSecret();

        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        if (StringUtils.isEmpty(memberSourceInfo.getIdcard()) || !IdcardUtil.isValidCard(memberSourceInfo.getIdcard())){
            return pushApiResult;
        }
        String idCardMd5 = SecureUtil.md5(memberSourceInfo.getIdcard());
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname());
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id_card_md5", idCardMd5);
        paramMap.put("name_md5", nameMd5);
        paramMap.put("phone_md5", mobileMd5);
        paramMap.put("time_stamp", timeStamp);
        paramMap.put("app_id", apiCode);
        paramMap.put("sign", SecureUtil.md5(apiCode+SecureUtil.md5(memberSourceInfo.getIdcard())+key+timeStamp));


        log.info("【融汇金服】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【融汇金服】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean isRepeat = data.getBoolean("is_repeat");
            if (!isRepeat){
                pushApiResult.setCode(code + "||" + isRepeat);
                pushApiResult.setPushSuccess(true);
                return pushApiResult;
            }
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String key = pushApiKeyParam.getApiSecret();
        String apiCode = pushApiKeyParam.getApiCode();

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("gender",memberSourceInfo.getSex() == 1 ? "男" : "女");
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        paramMap.put("phone",memberSourceInfo.getMobile());
        paramMap.put("id_card",memberSourceInfo.getIdcard());
        paramMap.put("zhimafen", RongHuiJinFuUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("region",memberSourceInfo.getProvince()+memberSourceInfo.getCity());
        paramMap.put("time_stamp",timeStamp);
        paramMap.put("is_expired",RongHuiJinFuUtil.getYuQi(memberSourceInfo.getYuqi()));
        paramMap.put("app_id",apiCode);
        paramMap.put("sign",SecureUtil.md5(apiCode+memberSourceInfo.getIdcard()+key+timeStamp));


        log.info("【融汇金服】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【融汇金服】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }






}
